# Copyright (c) 2020, Mopon.php
# All rights reserved.
# 文件名称： picListFrame.php
#https://www.cnblogs.com/saintdingspage/p/7730201.html

__author__ = "lishang"
__date__ = "$2021-7-2 11:30:25$"

import wx,time
import picmap

class picListFrame(wx.Frame):
    id=''
    pics=[]
    menuDefault={'操作':['打开','浏览','查看','全屏']}
    flagFullScreen=0
    filter={}
    def __init__(self,layout):
         wx.Frame.__init__(self,None,-1,u'图片列表',size=(1200,800))
         self.layout=layout
         self.menu(self.menuDefault)
         self.panel = wx.Panel(self,-1,size=wx.DisplaySize())
         self.panel.SetBackgroundColour('#999')
         self.panel.Bind(wx.EVT_CHAR_HOOK, self.onKeyDown1)

         self.panel2 = wx.Panel(self,-1,size=wx.DisplaySize())
         b=ImageWindow(self.panel2,wx.ID_ANY)
         b.Bind(wx.EVT_LEFT_DCLICK,self.dbclickPic)
        #  cb=wx.Button(self.panel2,-1,'关闭',pos = (150, 60), size = (100, 60))
        #  self.Bind(wx.EVT_BUTTON,self.hidePic,cb)
         self.panel2.SetBackgroundColour('#000')
         self.panel2.Hide()
         self.panel2.Bind(wx.EVT_MOUSEWHEEL, self.onMouse) 
         self.panel2.Bind(wx.EVT_CHAR_HOOK, self.onKeyDown)
         
         self.sizer=wx.GridSizer(cols=11, rows=9, vgap=10,hgap=5)
         self.panel.SetSizer(self.sizer)
         self.Center() 


        #  mypic = wx.EmptyBitmap(1200,800)
        # #  mypic = image.ConvertToBitmap()
        #  b=wx.BitmapButton(self.panel2,-1,mypic)
        #  b.SetBackgroundColour('#000')
        #  b.Bind(wx.EVT_LEFT_DOWN, self.MouseDown) 
        #  b.Bind(wx.EVT_LEFT_UP, self.MouseUp) 
        #  b.Bind(wx.EVT_MOTION, self.MouseMove) 
         
         self.Bind(wx.EVT_SIZE, self.onResize) 

         self.imageBox=b
         self.activeFile=-1

    def __del__(self):
        # self.layout.frameDict.clear('picList')
        pass
    
     #显示图片 
    def show(self,id,filter={}):
         self.id=id
         [x,y]=id.split(",")
         where="x like '%s' and y like '%s'" %(x+"%",y+"%")
         for k in filter:
             where+=" and %s like '%s'" %(k,filter[k]+"%")
         self.pics=picmap.db.queryObject('pic left join path on path.id=pic.pid',where ,'name,path,path||file as file,time')
         for i,p in zip(range(0,len(self.pics)),self.pics): 
             p['index']=str(i)
             self.picOne(p)
             
         (options,now)=picmap.filterOption(self.pics)         
         tree={now['name'] or '区域':options['name'],now['time'] or '时间':options['time'],now['path'] or '路径':options['path']}
        #  for k in self.menuDefault: 
        #      tree[k]=self.menuDefault[k]
         self.menu(tree)
         self.Show()
          
    def hidePic(self,event):
        self.panel2.Hide()
        self.activeFile=-1
        self.panel.Show(True)
        self.panel.SetFocus()
        
    def showPic(self,index):
        index=max(0,min(index,len(self.pics)-1))
        file=self.pics[index]['file']
        image = wx.Image(file,wx.BITMAP_TYPE_JPEG)
        [w,h]=self.Size
        

        img_h=min(h,image.GetHeight())*self.scale
        img_w= int(image.GetWidth()/(image.GetHeight()/img_h))
        image.Rescale(img_w,img_h)
        
        mypic = image.ConvertToBitmap()
        print([w,h,img_w,img_h])
        # wx.StaticBitmap(self.panel2, -1, wx.EmptyBitmap(w,h)) 
        w=int((w-img_w)/2)
        h=int((h-img_h)/2)
        if self.scale > 1: 
            s1=self.imageBox.Size
            p1=self.imageBox.GetPosition()
            x, y = wx.GetMousePosition()
            x1=x-p1.x; y1=y-p1.y
            s2=(img_w,img_h)
            x2=x1/(s1[0]/s2[0]); y2=y1/(s1[1]/s2[1])
            w=x-x2
            h=y-y2
            print([w,h])

        self.imageBox.SetSize(img_w,img_h)
        # self.bg=wx.StaticBitmap(self.panel2, -1, mypic, (w, h)) 
        self.imageBox.SetBitmap(mypic)
        self.imageBox.SetPosition(wx.Point(w,h))
        # self.imageBox.Refresh()
        self.panel2.Refresh()
        
        self.panel.Hide()
        self.panel2.Show(True)
        self.panel2.SetFocus()
        self.activeFile=index
#        picmap.pic.show(file)
    
    scale=1.0
    #缩放图片
    def scalePic(self,d):
        if d:
            self.scale+= 0.2
        else:
            self.scale-= 0.2
        self.scale=max(0,min(11,self.scale))    
        self.showPic(self.activeFile)
        pass

    def dbclickPic(self,event):
        self.scale+=2
        if self.scale>10 :  self.scale=1
        self.showPic(self.activeFile)

    def menu(self,tree,pmenu=None,floor=0):
        if not pmenu: 
            self.menubar = wx.MenuBar()
            self.SetMenuBar(self.menubar)       
            pmenu=self.menubar
#        map(pmenu.Remove,pmenu.GetMenus())
        for k in tree:
            mymenu=wx.Menu() if floor==0 else wx.NewId()
            pmenu.Append(mymenu, k)
            if  type(tree)== dict and  tree.get(k) : 
                self.menu(tree[k],mymenu,floor+1)
            elif type(mymenu) != int: 
                cm=wx.NewId()
                mymenu.Append(cm, " ")

        if floor ==0: 
            self.Bind(wx.EVT_MENU,self.onMenuClick)
            
        
#        pmenu.Refresh()  
    def onResize(self,event):
         if self.activeFile>-1:
              self.showPic(self.activeFile)
             
    def onMenuClick(self,event):
        print(event.GetEventObject())
        pass
        
    #https://www.pythonheidong.com/blog/article/306927/521cfdf9f4c60902c32c/
    #https://www.wxpython.org/Phoenix/docs/html/wx.KeyCode.enumeration.html#wx-keycode
    #
    def onKeyDown(self,event):
        keycode = event.GetKeyCode()
        if self.activeFile<0:
           if keycode==wx.WXK_ESCAPE:
                self.Hide()
           return event.Skip()
       
        print(keycode)       
        if keycode in [wx.WXK_BACK ,wx.WXK_PAGEUP]:
            index=self.activeFile - 1
            self.showPic(index)
        elif keycode in [wx.WXK_SPACE,wx.WXK_PAGEDOWN]:
            index=self.activeFile + 1
            self.showPic(index)
        elif keycode in [wx.WXK_LEFT,wx.WXK_RIGHT,wx.WXK_DOWN,wx.WXK_UP,wx.WXK_HOME,wx.WXK_END]:
                if self.scale ==1:
                    index=self.activeFile
                    if keycode == wx.WXK_LEFT:
                            index=index-1
                    elif keycode==wx.WXK_RIGHT:
                            index=index+1
                    elif keycode==wx.WXK_HOME:
                            index=0
                    elif keycode==wx.WXK_END:
                            index=len(self.pics)-1

                    if keycode in [wx.WXK_UP,wx.WXK_DOWN]:
                        self.scalePic(keycode==wx.WXK_UP)
                    else:
                        self.showPic(index)    
                    return

                mn=10
                pos=self.imageBox.GetPosition()
                if keycode in [wx.WXK_LEFT,wx.WXK_RIGHT]:
                    pos.x=pos.x-mn  if keycode!=wx.WXK_LEFT else pos.x+mn
                elif keycode in [wx.WXK_DOWN,wx.WXK_UP]:
                    pos.y=pos.y-mn  if keycode!=wx.WXK_UP else pos.y+mn
                elif keycode in [wx.WXK_HOME,wx.WXK_END]:
                    pos.y= 0 if keycode==wx.WXK_HOME else 0-(self.imageBox.Size[1]-self.Size[1])
                self.imageBox.SetPosition(pos)
        elif keycode==wx.WXK_ESCAPE:
                if self.scale!= 1: 
                    self.scale=1
                    self.showPic(self.activeFile)
                    return
                if self.flagFullScreen==1 : 
                    self.ShowFullScreen(False) 
                    self.flagFullScreen=0
                    return
                self.hidePic(event)
                
        elif  keycode==wx.WXK_F11: 
            if self.flagFullScreen==0: 
                self.ShowFullScreen(True) 
                self.flagFullScreen=1    
            else:
                self.ShowFullScreen(False) 
                self.flagFullScreen=0

    def onKeyDown1(self,event):
        keycode = event.GetKeyCode()
        if keycode==wx.WXK_ESCAPE:
            self.Close()

    def onMenuClick(self,event):
         menu=event.GetEventObject()
#         name=menu.GetLabelText()
         name=menu.GetTitle()
         index=1
         print(name)
         hander={
            '打开':self.opendir,
            '浏览':self.hidePic,
            '查看':lambda: self.showPic(0),
            '全屏':lambda: self.ShowFullScreen(True)
         }
         if hander.get(name):
             return hander[name]()
         
         map=['name','time','path']
         self.filter[map[index]]=pname+name
         self.show(self.id,self.filter)
         print(menu)
         print(menu.GetParent())
         pass
     
    def onPicClick(self,event):
        file=self.showPic(int(event.GetEventObject().GetName()))
        
    def  opendir():
        pass

    def onMouse(self,event):
         self.scalePic(event.GetWheelRotation()>0)
         
    def picOne(self,p):
        image = wx.Image(p['file'],wx.BITMAP_TYPE_JPEG)
        h= image.GetHeight()/(image.GetWidth()/200)
        image.Rescale(200,h)
        # b=ImageWindow(self,wx.ID_ANY)
        # b.SetImage(image)
        mypic = image.ConvertToBitmap()
        b=wx.BitmapButton(self.panel,-1,mypic,name=p['index'])
        b.SetWindowStyleFlag(wx.NO_BORDER)
        # b.SetBackgroundColour("#999")
        self.sizer.Add(b,0,wx.EXPAND,border= 2)
        self.Bind(wx.EVT_BUTTON,self.onPicClick,b)

class ImageWindow(wx.Window):
    
    def __init__(self,parent,id):
        wx.Window.__init__(self, parent, id)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.SetBackgroundColour('#000')
        self.Bind(wx.EVT_LEFT_DOWN, self.MouseDown) 
        self.Bind(wx.EVT_LEFT_UP, self.MouseUp) 
        self.Bind(wx.EVT_MOTION, self.MouseMove) 
        self.image = None
        self.bmap = None

    def SetBitmap(self,bmap):
        self.bmap = bmap
        self.Refresh(True)

    def SetImage(self, image):
        self.image = image
        self.Refresh(True)

    def OnPaint(self,evt):
        dc = wx.PaintDC(self)
        if self.image:
	        dc.DrawBitmap(self.image.ConvertToBitmap(), 0, 0, False)
        elif self.bmap:
            dc.DrawBitmap(self.bmap, 0, 0, False)

   # 按钮拖拽https://blog.csdn.net/wangqing008/article/details/38920629?locationNum=3&fps=1
    d={}         

    def MouseMove(self,event):
         try:
                if 'd' in self.d:
                    o = self.d['d']
                    x, y = wx.GetMousePosition()
                    o.SetPosition(wx.Point(x+o._x,y+o._y))
         except: pass
         pass

    def MouseDown(self,e):
        o           = e.GetEventObject()
        sx,sy       = self.ScreenToClient(o.GetPositionTuple())
        dx,dy       = self.ScreenToClient(wx.GetMousePosition())
        o._x,o._y   = (sx-dx, sy-dy)
        self.d['d'] = o
        # 光标样式 https://www.cnblogs.com/whwywzhj/p/6670470.html
        self.SetCursor( wx.StockCursor( wx.CURSOR_HAND ) ) 
#         self.pos=event.GetPositionTuple()#得到鼠标的位置
#        self.CaptureMouse()#捕获鼠标
        pass
        
    def MouseUp(self,e):
        self.SetCursor( wx.StockCursor( wx.CURSOR_ARROW ) ) 
        # try:
        if 'd' in self.d: 
            del self.d['d']
        # except: 
        #     pass